const fs = require('fs');
const path = require('path');
var jsonPath = path.join(__dirname, 'DataStorage/AccountList.json');

var accountList;

// 返回用户列表信息
module.exports.GetUserList = function () {
    fs.readFile(jsonPath, (err, data) => {
        if (err)
            console.log(err.message);

        accountList = JSON.parse(data.toString());

        console.log('共有：' + accountList.length + '个用户信息');
    });

    return accountList;
}

// 查询用户列表
module.exports.QueryUser = function () {

    fs.readFile(jsonPath, (err, data) => {
        if (err)
            console.log(err.message);

        accountList = JSON.parse(data.toString());

        console.log('共有：' + accountList.length + '个用户信息');
    });
}

// 判断是否登录成功，登录成功返回true，登录失败返回false
module.exports.LoginJudge = function (username, password, accountType) {
    var result = false;

    accountList.forEach(item => {
        if (item.username == username && item.password == password && item.accountType == accountType)
            result = true;
    });

    return result;
}

// 注册新用户
module.exports.AddNewUser = function (username, password, realName) {
    // 是否注册成功
    var isAddSuccess = true;

    var newAccount = {
        "username": username,
        "password": password,
        "realName": realName,
        "accountType": "normal"
    };

    // 如果后台用户列表中已经有同名的用户，则注册失败
    accountList.forEach(item => {
        if (item.username == newAccount.username || item.realName == newAccount.realName)
            isAddSuccess = false;
    })

    fs.readFile(jsonPath, (err, data) => {
        if (err)
            console.log(err.message);

        accountList = JSON.parse(data.toString());

        if (!isAddSuccess) {
            console.log('新用户添加失败');
        } else {
            accountList.push(newAccount);

            var jsonStr = JSON.stringify(accountList);

            fs.writeFile(jsonPath, jsonStr, err => {
                if (err) console.error(err.message);

                console.log("新用户添加成功!");
            })
        }
    })

    return isAddSuccess;
}

// 删除指定用户
module.exports.DeleteAppointedUser = function (username) {
    fs.readFile(jsonPath, (err, data) => {
        if (err)
            console.log(err.message);

        accountList = JSON.parse(data.toString());

        for(var i = 0 ; i< accountList.length ; i++ )
        {
            if(accountList[i].username == username)
            {
                accountList.splice(i,1);
            }
        }

        var jsonStr = JSON.stringify(accountList);

        fs.writeFile(jsonPath, jsonStr, err => {
            if (err) console.error(err.message);

            console.log("新用户添加成功!");
        });
    });
}


